import { McpServer, type ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export function registerPublishCcbTool(server: McpServer) {
  server.tool("publish-ccb",
    { index: z.coerce.number().int().positive().describe("要发布的资源索引号") },
    handleFunc
  );
}

// 根据错误信息，`ToolCallback` 泛型参数需要满足 `ZodRawShape` 约束，因此需要将 `{ index: number }` 改为 `{ index: z.ZodNumber }`
const handleFunc: ToolCallback<{ index: z.ZodNumber }> = async ({ index }) => {
    const { exec } = await import('child_process');
    const { promisify } = await import('util');
    const execPromise = promisify(exec);

    const appleScript = `
    tell application "Terminal"
        activate
        do script "sh /Users/ghost/toolKits/ghostStudio/ccbPublish.sh ${index.toString()}"
    end tell
    `;

    try {
        const { stdout } = await execPromise(`osascript -e '${appleScript.trim().replace(/'/g, "'\\''")}'`);
        return {
            content: [{
                type: "text",
                text: `终端已启动: ${stdout}`
            }]
        };
    } catch (error) {
        const err = error as { stderr?: string; message: string };
        return {
            content: [{
                type: "text",
                text: `启动失败: ${err.stderr || err.message}`
            }]
        };
    }
};